<template>

  <div class='product' v-if="pageLoading">
    <div class="swipes">
      <van-swipe :autoplay="5000" indicator-color="#B60102">
        <van-swipe-item v-for="(item, index) in image" :key="index">
          <van-image :src="`${resourceURL}/${item?.url}`" fit="cover" @click="imagePreviews(sildes,index)" />
        </van-swipe-item>
      </van-swipe>
      <div class="prices">
        <div class="sale_price">
          <span class="sale_price">￥{{product?.mprice}}</span>
          <span class="price">￥{{product?.price}}</span>
        </div>
        <div class="salecount">月销{{product?.salecount}}</div>
      </div>
    </div>

    <div class="info">
      <van-cell-group style="margin-top:0;" inset>
        <van-cell class="product_name" :title="product?.product_name" />
        <div class="options">

          <van-button v-if="is_coll==1" class="star " icon="star-o" @click="collectProctor(1)">收藏</van-button>
          <van-button v-else class="star is-star" icon="star-o " @click="collectProctor(2)">收藏</van-button>
          <van-button class="share" icon="share-o" @click="saveImage">分享</van-button>
        </div>
      </van-cell-group>

      <van-cell-group class="attribute" inset>
        <van-cell title="规格" :value="checkAttribute" is-link center @click="showSku = true" />
        <van-cell title="运费">
          <template #default>
            <div class="express_fee">
              <div v-if="product?.express_fee==0" class="fee">免运费</div>
              <div v-else>￥{{product?.express_fee}}</div>
            </div>
          </template>
        </van-cell>
      </van-cell-group>

      <hot-product title="商品推荐" :list="hotList" style="margin-top:12px;" @detail="goDetail" />

      <van-cell-group inset>
        <van-cell class="shop_name" :title="shop.shop_name" is-link center @click="goShop">
          <template #icon>
            <van-image class="shopcover" :src="`${resourceURL}${shop.imagesurl}`" fit="cover" />
          </template>
          <template #label>
            <div class="brand">品牌自营</div>
          </template>
        </van-cell>
      </van-cell-group>

      <van-cell-group inset>
        <van-cell class="commit_count" :title="`评价(${commit.length})`" value="查看全部" :border="false" is-link center :to="{name:'commitMore',query:{id}}" />
        <van-cell class="commit_item" v-if="commit[0]">
          <template #icon>
            <van-image class="usercover" :src="`${resourceURL}${commit[0].avatar}`" fit="cover" />
          </template>
          <template #title>
            <div class="username">
              <span>{{commit[0].nick_name}}</span>
              <span>{{formatCreateTime(commit[0].add_time)}}</span>
            </div>
            <div class="content">{{commit[0].content}}</div>
            <div class="evaluate_pic">
              <van-image v-for="(item, index) in commit[0].images" :key="index" :src="`${resourceURL}${item}`" fit="cover" @click="imagePreviews(commit[0].images,index)" />
            </div>
          </template>
        </van-cell>
        <van-empty v-else class="empty" description="暂无评价" />
      </van-cell-group>
    </div>

    <van-cell-group class="describe" inset>
      <div class="title_bg">商品详情</div>
      <div class="richtext" v-html="product?.describe"></div>
    </van-cell-group>

    <van-goods-action class="goods_action">
      <van-goods-action-icon :icon="require('@/assets/img/product/shop.png')" text="店铺" @click="goShop" />
      <!-- <van-goods-action-icon :icon="require('@/assets/img/product/service.png')" text="客服" @click="goCustomerService" /> -->
      <van-goods-action-button type="rgba(255,119,51,0.1)" color="#f8e5e5" text="加入购物车" class="add_card" @click="showSku = true" />
      <van-goods-action-button type="danger" color="#FF7733" text="立即购买" @click="showSku = true" />
    </van-goods-action>

    <!-- 选择商品规格 -->
    <van-popup class="skus" v-model="showSku" position="bottom" closeable :style="{ minHeight: '80%' }" round>
      <div>
        <div class="sku_product">
          <van-image :src="`${resourceURL}${product?.imageurl}`" fit="cover" />
          <div class="sku_info">
            <div class="sku_sale_price">￥{{product?.mprice}}</div>
            <div class="sku_price">
              <span class="price">原价￥{{product?.price}}</span>
              <van-stepper class="stepper" v-model="stepper" input-width="50px" button-size="26px" disable-input />
            </div>
          </div>
        </div>
        <div class="sku_specifications">
          <div class="title">规格</div>
          <div class="list">
            <div class="item" v-for="(item, index) in stock" :key="index" :class="{is_active:skuActive == item.p_s_id}" @click="checkSku(item.p_s_id)">
              {{item?.p_s_name}}
            </div>
          </div>
        </div>
      </div>
      <div class="sku_btn">
        <van-button class="add_card btn1" type="warning" color="#f8e5e5" text="加入购物车" @click="onAddCartClicked('cart')" />
        <van-button class="btn2" type="danger" color="#B60102" text="立即购买" @click="onAddCartClicked('buy')" />
      </div>
    </van-popup>

    <van-overlay :show="showShare" @click="showShare = false">

      <img id="poster" class="poster" />
    </van-overlay>

    <div class="shareBox" ref="element">
      <div class="round">

        <div class="img">
          <van-image :src="`${resourceURL}/${image[0].url}`" fit="cover" />

        </div>

      </div>
      <div class="top">
        <div class="price"><span style=" font-size: 12px;">￥</span>{{ product.mprice}}</div>
        <div class="name">{{ product.product_name}}</div>
        <div class="codeBox" ref="qrCode"></div>
      </div>
      <van-button type="primary" round :icon="require('../../assets/img/微信.png')" color="#ff7733">长按进行保存</van-button>
      <div class="store">
        <van-image :src="require('../../assets/img/store.png')" fit="cover" />
        <div class="shop_name">{{ shop.shop_name }}</div>
      </div>
    </div>
  </div>
</template>

<script>
import HotProduct from '@/components/hotProduct'
import { ImagePreview, Toast } from 'vant'
import QRCode from 'qrcodejs2'
import html2canvas from "html2canvas"
export default {
  components: { HotProduct },
  data () {
    return {
      id: null,
      pageLoading: false,
      showShare: false,
      haveCode: false,
      product: {},
      sildes: [],
      hotList: [],
      commit: [],
      skuList: [],
      stepper: 1,
      skuActive: null,
      checkAttribute: '请选择',
      showSku: false,
      image: '',
      shop: "",
      stock: '',
      show: false,
    }
  },
  created () {
    this.id = this.$route.query.id
    this.getProductDetail()

  },
  mounted () {

    console.log(this.$store.state.userInfo.user_id);

  },
  computed: {
    // 格式化评论时间
    formatCreateTime () {
      return function (val) {
        return this.$moment(Number(val) * 1000).calendar(null, {
          sameDay: '[今天]',
          nextWeek: 'YYYY-MM-DD',
          lastDay: '[昨天]',
          lastWeek: 'YYYY-MM-DD',
          sameElse: 'YYYY-MM-DD'
        });
      }
    }
  },

  methods: {
    // 保存图片
    saveImage () {

      if (!this.haveCode) {

        let qrcode = new QRCode(this.$refs.qrCode, {
          text: 'Hellow QRCode!',
          width: (window.innerWidth) * (84 / 375),
          height: (window.innerWidth) * (84 / 375),
          colorDark: "black", // 二维码颜色
          colorLight: "#ffffff", // 二维码背景色
          correctLevel: QRCode.CorrectLevel.H // 容错率,L:容错率为 7%;M:容错率为 15%;Q:容错率为 25%;H:容错率为 30%. PS:容错级别越高抗残破或遮挡的能力就越强
        });
        qrcode.makeCode(`${window.location.href}&from_uid=${this.$store.state.userInfo.user_id}`)


        const img1 = document.querySelector('#poster')
        html2canvas(this.$refs.element, {
          useCORS: true,
        }).then(canvas => {
          const dataURL = canvas.toDataURL("image/png");
          img1.src = dataURL

        })
        this.haveCode = true
      }
      this.showShare = true

    },
    // 获取商品详情
    getProductDetail () {
      Toast.loading({ message: '加载中...', duration: 0 })
      this.$axios.get(this.$api.getproductdetail, {
        params: {
          product_id: this.id
        }
      }).then(res => {
        this.pageLoading = true
        Toast.clear()
        this.product = res.data.data.product

        this.image = res.data.data.image.length ? res.data.data.image : [{ url: res.data.data.product.imageurl }]

        this.shop = res.data.data.shop
        this.is_coll = res.data.data.is_coll
        this.stock = res.data.data.stock

        // let silde = res.data.data.products.images.map(e => {
        //   return e.url
        // })
        // silde.unshift(res.data.data.products.imageurl)
        //this.spliceingImageUrl(silde, this.sildes)
        this.getHotProduct(this.shop.shop_id)
        this.getProductCommit()
      })
    },
    // 获取商品推荐
    getHotProduct (id) {
      this.$axios.get(this.$api.gethotproduct, {
        params: {
          shop_id: id
        }
      }).then(res => {
        this.hotList = res.data.data.data
      })
    },
    // 获取商品评价
    getProductCommit () {
      this.$axios.get(this.$api.getproductcommit, {
        params: {
          product_id: this.id
        }
      }).then(res => {
        this.commit = res.data.data.data
      })
    },
    // 收藏商品
    collectProctor () {
      this.$axios.post(this.$api.collectproduct, {
        product_id: this.id
      }).then(res => {
        if (res.data.code == 1) {
          if (this.is_coll == 1) {
            Toast.success({ message: '收藏成功' });
          } else {
            Toast.fail({ message: '取消收藏' });
          }
        } else {
          Toast({ message: res.data.msg });
        }
        setTimeout(() => {
          this.$router.replace({ name: 'product', query: { id: this.id } });
          location.reload()
        }, 1000);
      })
    },

    // 查看其他、热门商品
    goDetail (id) {
      this.$router.push({ name: 'product', query: { id } });
      location.reload()
    },
    // 查看店铺
    goShop () {
      this.$router.push({ name: 'store', query: { id: this.product.shop_id } });
    },
    // 选择规格、取消选择
    checkSku (id) {
      if (this.skuActive && this.skuActive == id) {
        this.skuActive = null
      } else {
        this.skuActive = id
      }
    },
    // 图片预览
    imagePreviews (array, index) {
      let newArr = []
      for (let index = 0; index < array.length; index++) {
        if (array[index].indexOf(this.resourceURL) == -1) {
          let element = this.resourceURL + array[index];
          newArr.push(element)
        } else {
          newArr = array
          break;
        }
      }
      ImagePreview({
        images: newArr,
        startPosition: index,
      });
    },
    // 加入购物车 or 立即购买
    onAddCartClicked (str) {
      this.$axios.post(this.$api.usereditcart, {
        product_id: this.id, //商品id
        stock_id: this.skuActive,// 规格id
        quantity: this.stepper,// 数量
      }).then(res => {
        const cart_id = res.data.data
        if (res.data.code == 1) {
          if (str == 'buy') {
            Toast.loading('正在下单')
            this.$store.commit('setcart_id', cart_id)
            setTimeout(() => {
              this.$router.push({ name: 'settlement' });
            }, 1000);
          }
          if (str == 'cart') {
            Toast.loading({ message: '加入购物车成功', duration: 1000 })
          }
        } else {
          Toast.fail(res.data.msg)
        }

      })
    },


  },
}
</script>

<style scoped lang='less'>
.overlay {
  .img {
    position: absolute;
    right: 23px;
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    /deep/ .van-image {
      width: 59px;
      height: 94px;
    }
    p {
      font-size: 16px;
      font-family: Microsoft YaHei-Bold, Microsoft YaHei;
      font-weight: bold;
      color: #ffffff;
    }
  }
}
.product {
  min-height: calc(100vh -60px);
  padding-bottom: 60px;
  .swipes {
    position: relative;
    /deep/.van-image {
      width: 100%;
      height: 375px;
    }
    /deep/.van-swipe__indicator {
      width: 12px;
      border-radius: 3px;
      background-color: #fff;
      opacity: 0.6;
    }
    /deep/.van-swipe__indicators {
      bottom: 60px;
    }
    /deep/.van-swipe__indicator--active {
      width: 6px;
      opacity: 1;
    }
    .prices {
      position: absolute;
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      width: 343px;
      height: 96px;
      padding: 12px 16px;
      margin: -50px 16px 0;
      border-radius: 16px;
      background: #ff7733;
      background-size: cover;
      background-position: 100% 100%;
      box-sizing: border-box;
      .sale_price {
        color: #ffffff;
        font-size: 20px;
        font-weight: bold;
      }
      .price {
        color: #ffffff;
        font-size: 12px;
        font-weight: 400;
        margin-left: 12px;
        text-decoration: line-through;
      }
      .salecount {
        color: #fff;
        font-size: 14px;
        line-height: 26px;
      }
    }
  }
  .info {
    .van-cell-group--inset {
      margin-top: 12px;
    }
    .product_name {
      color: #470607;
      font-size: 16px;
      font-weight: bold;
      padding: 16px 16px 14px;
      word-break: break-all;
      white-space: pre-wrap;
    }
    .options {
      display: flex;
      justify-content: space-between;
      padding: 0;
      box-sizing: border-box;
      .star {
        color: #757472;
        background: transparent !important;
        border-color: transparent !important;
      }
      .is-star {
        color: #f9c254;
      }
      .share {
        color: #f9c254;
        background: transparent !important;
        border-color: transparent !important;
      }
      /deep/.van-button {
        flex: 1;
        .van-button__content {
          align-items: center;
          font-size: 16px;
        }
      }
    }
    .attribute {
      .van-cell {
        padding: 12px 16px;
      }
      /deep/.van-cell__title {
        color: #757472;
      }
      /deep/.van-cell__value {
        color: #bab9b8;
      }
      .express_fee {
        display: flex;
        justify-content: flex-end;
      }
      .fee {
        font-size: 14px;

        font-weight: 400;
        color: #202327;
      }
    }
    .shop_name {
      padding: 16px;
      /deep/.van-cell__title {
        color: #000;
        font-size: 16px;
        font-weight: bold;
      }
      .shopcover {
        width: 48px;
        height: 48px;
        border-radius: 6px;
        margin-right: 12px;
        overflow: hidden;
      }
      .brand {
        width: 70px;
        height: 19px;
        line-height: 19px;
        font-size: 12px;
        color: #b60102;
        text-align: center;
        background: url('../../assets/img/product/brand.png') no-repeat;
        background-size: cover;
        background-position: 100% 100%;
      }
    }
    .commit_count {
      .van-cell__title {
        font-size: 14px;
      }
      .van-cell__value {
        font-size: 12px;
      }
    }
    .commit_item {
      .usercover {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        margin-right: 10px;
        overflow: hidden;
      }
      .username {
        display: flex;
        justify-content: space-between;
        color: #909090;
        span:nth-child(1) {
          max-width: 150px;
          font-size: 14px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        span:nth-child(2) {
          font-size: 12px;
        }
      }
      .content {
        margin-top: 5px;
      }
      .evaluate_pic {
        display: flex;

        .van-image {
          width: 84px;
          height: 84px;
          border-radius: 10px;
          margin-top: 8px;
          overflow: hidden;
          margin-left: 6px;
        }
      }
    }
    .empty {
      padding: 0 0 10px;
      /deep/ .van-empty__image {
        width: 106px;
        height: 106px;
      }
    }
  }
  .describe {
    min-height: 300px;
    margin-top: 12px;
    .title_bg {
      height: 53px;
      font-size: 16px;
      font-family: Microsoft YaHei-Regular, Microsoft YaHei;
      font-weight: 400;
      color: #201d1d;
      line-height: 53px;
      //text-align: center;
      text-indent: 0.75em;
      //background: url('../../assets/img/product/product-detail.png') no-repeat;
      // background-size: contain;
      // background-position: 100% 100%;
    }
    .richtext {
      /deep/p {
        padding: 0;
        margin: 0;
        line-height: 26px;
        word-break: break-all;
        word-wrap: break-word;
      }
      /deep/ img {
        display: block;
        width: 100%;
        height: 100%;
      }
    }
  }
  .add_card /deep/.van-button__text {
    color: #ff7733;
  }
  .skus {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    padding: 20px 16px;
    box-sizing: border-box;
    .sku_product {
      display: flex;
      height: 60px;
      margin-bottom: 30px;
      .van-image {
        width: 60px;
        height: 60px;
        border-radius: 6px;
        margin-right: 10px;
        overflow: hidden;
      }
      .sku_info {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        .sku_sale_price {
          font-size: 18px;
          color: #fb2b2c;
          font-weight: bold;
        }
        .sku_price {
          display: flex;
          justify-content: space-between;
          align-items: flex-end;
          & .price {
            color: #686868;
            font-size: 12px;
          }
          .stepper {
            /deep/.van-stepper__plus,
            /deep/.van-stepper__minus {
              background-color: #fff;
              border: 1px solid #dfdfdf;
            }
            /deep/ .van-stepper__input {
              margin: 0;
              background-color: #fff;
              border-top: 1px solid #dfdfdf;
              border-bottom: 1px solid #dfdfdf;
            }
          }
        }
      }
    }
    .sku_specifications {
      .title {
        font-size: 12px;
        margin-bottom: 10px;
      }
      .list {
        display: flex;
        flex-flow: row wrap;
        max-height: 320px;
        overflow: auto;
        .item {
          color: #000;
          font-size: 12px;
          padding: 6px 18px;
          margin: 0 16px 10px 0;
          background-color: #fff;
          border: 1px solid #b4b2b2;
          border-radius: 6px;
          transition: 0.25s;
        }
        .is_active {
          color: #fff;
          background-color: #ff7733;
          border: 1px solid #ff7733;
        }
      }
    }
    .sku_btn {
      display: flex;
      .van-button {
        flex: 1;
      }
      .btn1 {
        border-radius: 50px 0 0 50px;
        background: rgba(255, 119, 51, 0.1) !important;
        color: #ff7733 !important;
      }
      .btn2 {
        border-radius: 0 50px 50px 0;
        background: #ff7733 !important;
        border: 1px solid #ff7733 !important ;
      }
    }
  }
}
.shareBox {
  position: absolute;
  top: 0;
  z-index: -99;
  width: 294px;

  background: #ffffff;
  border-radius: 6px;
  border: 2px solid #f33224;
  overflow: hidden;

  .round {
    width: 700px;
    height: 600px;
    border-radius: 50%;
    position: absolute;
    top: -94.5%;
    left: -66.5%;
    overflow: hidden;
    .img {
      z-index: 2;
      position: absolute;

      top: 59%;
      left: 28%;
      .van-image {
        width: 294px;
        height: 290px;
      }
    }
  }
  .top {
    margin-top: 240px;
    margin-left: 11px;
    position: relative;
    z-index: 99;
    .price {
      font-size: 20px;
      font-weight: bold;
      color: #f33224;
    }
    .name {
      font-size: 16px;
      font-weight: bold;
      color: #202327;
    }
    .codeBox {
      width: 84px;
      height: 84px;
      background: #000;
      position: absolute;
      top: -125%;
      left: 68%;
    }
  }
  .van-button {
    margin-left: 11px;
    margin-top: 12px;
    width: 270px;
    height: 44px;
    // background: #ff7733;
    // border: 1px soli;
  }
  .store {
    margin: 11px 0;
    display: flex;
    align-items: center;
    margin-left: 11px;
    .van-image {
      width: 17px;
      height: 17px;
    }
    .shop_name {
      margin-left: 6px;
      font-size: 12px;

      color: #06021a;
    }
  }
}
.van-overlay {
  display: flex;
  justify-content: center;
  align-items: center;
  #poster {
    width: 294px;
    height: 376px;
  }
}
</style>
